var utility     = require('system/utility'),
    events      = require('events'),
    Http        = require('http'),
    url         = require("url");
    queryString = require('querystring'),
	Stream      = require('stream');

HttpRouter = (function() {
	var HttpRouter = function(settings) {
		var me = this;

		me._server   = Http.createServer();
		me._settings = utility.extend(
			{
				router : undefined
			},
			settings
		);

		me._server.on('connection', function(socket) { me._onConnection(socket); });
		me._server.on('request', function(request, response) { me._onRequest(request, response); } );
		me._server.on('error', function(err) { me._onError(err); });
		me._server.on('close', function() { me._onClose(); });
		me._server.on('listening', function() { me._onListening(); });

		events.EventEmitter.call(me);
	};

	utility.inherits(HttpRouter, events.EventEmitter);

	HttpRouter.prototype.listen = function() {
		 this._server.listen.apply(this._server, arguments);
	};

	HttpRouter.prototype.close = function() {
		this._server.close();
	};

	HttpRouter.prototype._onConnection = function(socket) {
		socket.on('data', this._onData);
	}

	HttpRouter.prototype._onRequest = function(request, response) {
		var me  = this,
		    uri = url.parse(request.url, true);
console.log('onRequest');
		if (request.method === 'POST') {
			var body = '';

			request.on('data', function(data) {
				body += data;
			});

			request.on('end', function () {
				var data = queryString.parse(body);

				utility.extend(data, uri.query);

				me._handleRequest(uri.pathname, data, response);
			});
		} else {
			me._handleRequest(uri.pathname, uri.query, response);
		}
	};

	HttpRouter.prototype._handleRequest = function(path, data, response) {
		var me = this;

		me._settings.router.execute(
			{
				path     : path,
				data     : data,
				callback : function(result) {
					if (result instanceof Stream) {
						result.on('data', function(data) {
							response.write(data);
						});

						result.on('end', function() {
							response.end();
						});
					} else {
						if (result instanceof Object) {
							result = JSON.stringify(result);
						}

						response.end(result);
					}
				}
			}
		);
	}

	HttpRouter.prototype._onError = function(err) {
		this.emit('error', err);
	};

	HttpRouter.prototype._onClose = function() {
		this.emit('close');
	};

	HttpRouter.prototype._onListening = function() {
		this.emit('listening');
	};

	HttpRouter.prototype._onData = function(data) {
		console.log('ondata ', data.toString());
	}

    // out to global
    return HttpRouter;
})()

// Hook into commonJS module systems
if (typeof module !== 'undefined' && "exports" in module) {
  module.exports = HttpRouter;
}